package persistence.hibernate;

import org.hibernate.SessionFactory ;
import org.hibernate.cfg.Configuration ;

import persistence.PersistenceFactory ;
import persistence.PersistenceController ;

/**
 * @author idan
 *
 */
public class HibernatePersistenceFactory implements PersistenceFactory
{
	private boolean loadOnStartup ;
	private SessionFactory sessionFactory ;

	/**
	 * @param loadOnStartup whether to load elements on startup or start a fresh database.
	 */
	public HibernatePersistenceFactory(final boolean loadOnStartup)
	{
		this.loadOnStartup = loadOnStartup ;
		Configuration config = new Configuration() ;
		this.sessionFactory = config.configure().buildSessionFactory() ;
	}

	/**
	 * @return hibernate's session factory.
	 */
	public SessionFactory getSessionFactory()
	{
		return this.sessionFactory ;
	}

	/**
	 * @see persistence.PersistenceFactory#loadingFromExisting()
	 */
	@Override
	public boolean loadingFromExisting()
	{
		return this.loadOnStartup ;
	}

	/**
	 * @see persistence.PersistenceFactory#newDirecoryPersistence()
	 */
	@Override
	public PersistenceController newDirecoryPersistence()
	{
		return new HibernatePersistenceController(domain.message.Directory.class, this.loadOnStartup,
			this.sessionFactory) ;
	}

	/**
	 * @see persistence.PersistenceFactory#newLoginPersistence()
	 */
	@Override
	public PersistenceController newLoginPersistence()
	{
		return new HibernatePersistenceController(domain.user.Login.class, this.loadOnStartup,
			this.sessionFactory) ;
	}

	/**
	 * @see persistence.PersistenceFactory#newMemberPersistence()
	 */
	@Override
	public PersistenceController newMemberPersistence()
	{
		return new HibernatePersistenceController(domain.user.Member.class, this.loadOnStartup,
			this.sessionFactory) ;
	}

	/**
	 * @see persistence.PersistenceFactory#newPostPersistence()
	 */
	@Override
	public PersistenceController newPostPersistence()
	{
		return new HibernatePersistenceController(domain.message.Post.class, this.loadOnStartup,
			this.sessionFactory) ;
	}

	/**
	 * @see persistence.PersistenceFactory#newThreadPersistence()
	 */
	@Override
	public PersistenceController newThreadPersistence()
	{
		return new HibernatePersistenceController(domain.message.Thread.class, this.loadOnStartup,
			this.sessionFactory) ;
	}

}
